<template>
  <div class="body" id="bodyRef">
    <div v-for="item in state.guidePaperList" :key="item.id">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>知识点：{{ item.knowledgepoint_cn }}</span>
            <span>类型：{{ item.type_cn }}</span>
            <span>创建者：{{ item.owner_info.nickname }}</span>
            <span>日期：{{ item.add_date }}</span>
            <span>库币：{{ item.bank_point }}</span>
            <el-tooltip class="box-item" effect="light" content="报告错误" placement="top">
              <el-button :icon="QuestionFilled" size="small" @click="submitFeedbackPaperClick(item)"></el-button>
            </el-tooltip>
          </div>
        </template>
        <div class="card_content">
          <div v-if="item.file != ''">
            <el-text class="mx-1" type="warning" size="large">{{ item.title }}</el-text>
            <el-button type="primary" size="large" text
              @click="downloadGuidePaperClick(item.id, item.title, item.type)">下载</el-button>

          </div>
          <span>介绍：</span>
          <div v-html="item.remark" class="line-break"></div>
          <div>
            <el-button size="small" type="primary" @click="viewPaperClick(item.file)">预览</el-button>
          </div>
        </div>
      </el-card>
    </div>
    <div class="pagination">
      <el-pagination background layout="total, pre, pager, next, jumper" :total="state.total" :page-size="state.pageSize"
        @current-change="handleCurrentChange" />
    </div>
    <!-- <FeedbackPaperBugDialog ref="feedbackPaperBugDialog" :file="state.file"></FeedbackPaperBugDialog> -->
    <ShowGuidePaperFileDialog ref="showGuidePaperFileDialog" :file="state.file"></ShowGuidePaperFileDialog>
  </div>
</template>  

<script setup>
import { reactive, onMounted, onUnmounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from '@/utils/axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import config from '~/config'
import ShowGuidePaperFileDialog from '@/components/ShowGuidePaperFileDialog.vue'
// import FeedbackPaperBugDialog from '@/componnts/FeedbackPaperBugDialog.vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import { Base64 } from 'js-base64';
import { localGet, onlinePreview } from '@/utils'

let localUser = localGet('user_information')
const feedbackPaperBugDialog = ref(null)
const showGuidePaperFileDialog = ref(null)
const route = useRoute()
const router = useRouter()
let baseDownloadUrl = config[import.meta.env.MODE].baseUrl_noapi  // 域名
//提交题目bug反馈
const submitFeedbackPaperClick = (item) => {
  // if (item) {
  //   feedbackPaperBugDialog.value.open(item)
  // }
}
//点击浏览导学案/课件文件的按钮事件处理
const viewPaperClick = (file) => {
  file = config[import.meta.env.MODE].baseUrl_noapi + file
  console.log("file", file)
  window.open(onlinePreview + encodeURIComponent(Base64.encode(file)));
  // showGuidePaperFileDialog.value.open(file)
}
const state = reactive({
  guidePaperList: [],
  knowledgeId: 0,
  total: 0,
  pageSize: 10,
  currentPage: 1,
  file: '',
  paymentAmount: 0,
})
const fileName = (title, file_type) => {
  if (file_type == 1 || file_type == 3) {
    return title + ".docx"
  } else {
    return title + ".pptx"
  }
}

onMounted(() => {
  const { id } = route.query
  if (id != undefined & id > 0) {
    state.knowledgeId = id;
  }
  getAllGuidePapers()
})
//监听路由变化
const unWatch = router.beforeEach((to, from, next) => {
  const { id } = to.query
  console.log("我是监听路由id", id)
  if (id != undefined & id > 0 & id != state.knowledgeId) {
    state.knowledgeId = id;
    getAllGuidePapers()
  }
  next(true)
})
onUnmounted(() => {
  unWatch()
})
const handleCurrentChange = (newPage) => {
  state.currentPage = newPage
  getAllGuidePapers()
  document.querySelector('#bodyRef').scrollIntoView(true);
}
// 获取点击章节目录后，发送过来的知识点下的所有导学案
const getAllGuidePapers = () => {

  let server_api = 'GuidePaperModelViewSet/knowledgepoint/'
  let params = {
    page: state.currentPage,
    size: state.pageSize,
    id: state.knowledgeId,
  }
  if (state.knowledgeId <= 0) {
    server_api = 'GuidePaperModelViewSet/all_online_public/'
  }
  axios.get(server_api, { params }).then(res => {
    if (res.code == 200) {
      // console.log("导学案列表：",res.data.results)
      state.guidePaperList = res.data.results
      state.total = res.total
      scrollToTop()
    } else {
      ElMessage("获取导学案失败")
      console.log("获取导学案失败：", res)
      state.total = 0
      if (res.code == 403) {
        ElMessage.error("请重新登录")
        router.push("/login")
      }
    }
  })
    .catch((error) => {
      console.log("获取导学案错误：", error)
    })
}
// 滚到页面顶端
const scrollToTop = () => {
  document.querySelector('#bodyRef').scrollIntoView(true);
}
// 查询选中的导学案费用
function queryFei(paper_id) {
  let params = {
    paper_id: paper_id,
  }
  axios.get('/PaymentAmountWithDownloadPaperApiView/', { params }).then(res => {
    if (res.code == 200) {
      state.paymentAmount = res.data.results
      console.log('最早查到金额：', state.paymentAmount)
      return res.data.results
    } else {
      ElMessage.warning('sorry，查询下载所需的库币错误')
      return -1
    }
  })
    .catch((error) => {
      console.log("下载库币查询失败", error)
      return false
    })
}

// 下载导学案
const downloadGuidePaperClick = (paper_id, title, file_type) => {
  let fileType = ['', 'docx', 'pptx']
  ElMessageBox.confirm(
    `确定下载${title}.${fileType[file_type]}吗？`,
    '下载文件',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      ElMessage({
        type: 'success',
        message: '将要下载文件!',
      })
      console.log("将要下载导学案id", paper_id)
      downloadPaper(paper_id)
    })
    .catch(() => {
      ElMessage({
        type: 'error',
        message: '取消下载',
      })
    })
}

// 发送下载导学案请求
const downloadPaper = (paper_id) => {
  console.log("你的库币：", localUser.bank_point)
  console.log("导学案的库币：", state.paymentAmount)
  if (localUser.bank_point < state.paymentAmount) {
    ElMessage.warning("库币不足");
    return false;
  }
  let params = {
    paper_id: paper_id,
  }
  axios.post('/PaymentAmountWithDownloadPaperApiView/', params).then(res => {
    if (res.code == 200) {
      let url = res.data.results
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'download.docx');
      // link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link)
    } else {
      ElMessage.warning('sorry,下载失败')
    }
  })
    .catch((error) => {
      console.log("下载错误：", error)
      return false
    })
}
</script>
<style scoped>
.body {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-items: stretch;
  overflow-y: auto;
  margin: 0;
  padding: 0;
}

.box-card {
  display: flex;
  flex-flow: column wrap;
  align-items: stretch;
  height: auto;
  width: 100%;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  margin: 0;
  padding: 0;
  height: 20px;
}

.card_content {
  display: flex;
  flex-flow: column wrap;
  margin: 0px;
  padding: 0px;
}

.line-break {
  white-space: pre-wrap;
  width: 950px;
  font-size: 14px;
}
</style>